package com.zzf.sus_time

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.app.ActivityCompat.requestPermissions
import androidx.core.content.ContextCompat.checkSelfPermission
import com.zzf.sus_time.ClockService

class MainActivity : ComponentActivity() {
    private lateinit var requestPermissionLauncher: ActivityResultLauncher<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        // ✅ 初始化通知权限请求器
        requestPermissionLauncher = registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted: Boolean ->
            if (isGranted) {
                Toast.makeText(this, "通知权限已授予", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "通知权限被拒绝，通知可能无法显示", Toast.LENGTH_SHORT).show()
            }
        }

        setContent {
            ClockSettingsUI()
        }
    }




}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ClockSettingsUI() {
    val context = LocalContext.current
    var fontSize by remember { mutableStateOf("") }
    var fontColor by remember { mutableStateOf(Color.Red) } // 改为 Color 类型

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp)
    ) {
        OutlinedTextField(
            value = fontSize,
            onValueChange = { fontSize = it },
            label = { Text("字体大小（如 20）") },
            modifier = Modifier.fillMaxWidth()
        )

        Spacer(modifier = Modifier.height(12.dp))

        // ✅ 使用抽离出来的 ColorPickerButton
        ColorPickerButton(
            selectedColor = fontColor,
            onColorSelected = { color ->
                fontColor = color // 更新颜色
            }
        )

        Spacer(modifier = Modifier.height(24.dp))

        Button(
            onClick = {
                val activity = context as? ComponentActivity
                if (activity == null) {
                    Toast.makeText(context, "Activity 上下文无效", Toast.LENGTH_SHORT).show()
                    return@Button
                }

//                // Android 13+ 通知权限检查
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//                    if (checkSelfPermission(context, android.Manifest.permission.POST_NOTIFICATIONS) !=
//                        android.content.pm.PackageManager.PERMISSION_GRANTED
//                    ) {
//                        requestPermissions(
//                            activity,
//                            arrayOf(android.Manifest.permission.POST_NOTIFICATIONS),
//                            1001
//                        )
//                        Toast.makeText(context, "请先授予通知权限", Toast.LENGTH_SHORT).show()
//                        return@Button
//                    }
//                }


                if (!Settings.canDrawOverlays(context)) {
//                    val intent = Intent(
//                        Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
//                        Uri.parse("package:${context.packageName}")
//                    )
//                    context.startActivity(intent)
//                    Toast.makeText(context, "请授予悬浮窗权限", Toast.LENGTH_SHORT).show()

                    OverlayPermissionHelper.requestOverlayPermission(context)

                } else {

                    try {
                        val stopIntent = Intent(context, ClockService::class.java)
                        context.stopService(stopIntent)
                        // 将 Color 转换为十六进制字符串
                        val colorHex = "#%06X".format(0xFFFFFF and fontColor.toArgb())
                        val intent = Intent(context, ClockService::class.java).apply {
                            putExtra("textSize", fontSize.toFloatOrNull() ?: 20f)
                            putExtra("textColor", colorHex)
                        }
                        // 停止现有服务
                        context.startForegroundService(intent)
                        //context.startService(intent) // 兼容 Android 8.0 以下版本
                        Toast.makeText(context, "已尝试启动服务", Toast.LENGTH_SHORT).show()
                    } catch (e: Exception) {
                        Toast.makeText(context, "启动服务失败: ${e.message}", Toast.LENGTH_LONG).show()
                        e.printStackTrace()
                    }
                }
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("启动悬浮时钟")
        }
    }


}


@Composable
fun ColorPickerButton(
    selectedColor: Color,
    onColorSelected: (Color) -> Unit
) {
    var showColorPicker by remember { mutableStateOf(false) }

    // 颜色选择按钮（方块预览）
    Row(verticalAlignment = Alignment.CenterVertically) {
        Text("选择字体颜色", fontSize = 16.sp)
        Spacer(modifier = Modifier.width(16.dp))
        Box(
            modifier = Modifier
                .size(32.dp)
                .background(selectedColor)
                .clickable { showColorPicker = true }
        )
    }

    // 显示颜色选择器
    if (showColorPicker) {
        AlertDialog(
            onDismissRequest = { showColorPicker = false },
            title = { Text("选择字体颜色") },
            text = {
                Column {
                    Row {
                        listOf(
                            Color.Red, Color.Green, Color.Blue,
                            Color.Black, Color.White, Color.Yellow, Color.Cyan
                        ).forEach { color ->
                            Box(
                                modifier = Modifier
                                    .size(40.dp)
                                    .padding(4.dp)
                                    .background(color)
                                    .clickable {
                                        onColorSelected(color) // 选择颜色后更新颜色
                                        showColorPicker = false
                                    }
                            )
                        }
                    }
                }
            },
            confirmButton = {},
            dismissButton = {}
        )
    }
}




